'use client';

import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import { message } from 'antd';
import { AuthContextType, AuthUser, LoginResponse, ApiResponse } from '@/types/auth';
import { tokenManager, userManager, validateToken, clearAuth, addAuthHeader } from '@/utils/auth';

const AuthContext = createContext<AuthContextType | undefined>(undefined);

interface AuthProviderProps {
  children: ReactNode;
}

export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
  const [user, setUser] = useState<AuthUser | null>(null);
  const [token, setToken] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const router = useRouter();
  const pathname = usePathname();

  // 公开路由（不需要登录）
  const publicRoutes = ['/login'];

  // 检查是否为公开路由
  const isPublicRoute = (path: string): boolean => {
    return publicRoutes.some(route => path.startsWith(route));
  };

  // 检查认证状态
  const checkAuth = async (): Promise<boolean> => {
    try {
      const storedToken = tokenManager.getToken();
      const storedUser = userManager.getUser();

      if (!storedToken || !storedUser) {
        clearAuth();
        return false;
      }

      // 验证 token 格式
      if (!validateToken(storedToken)) {
        clearAuth();
        return false;
      }

      // 验证 token 是否仍然有效（调用后端）
      const response = await fetch('/api/auth/me', {
        method: 'GET',
        headers: addAuthHeader(),
      });

      if (response.ok) {
        const result: ApiResponse<AuthUser> = await response.json();
        if (result.success && result.data) {
          setUser(result.data);
          setToken(storedToken);
          // 更新存储的用户信息
          userManager.setUser(result.data);
          return true;
        }
      }

      // 如果验证失败，清除认证信息
      clearAuth();
      return false;
    } catch (error) {
      console.error('认证检查失败:', error);
      clearAuth();
      return false;
    }
  };

  // 登录函数
  const login = async (username: string, password: string) => {
    try {
      const response = await fetch('/api/auth/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ username, password }),
      });

      const result: LoginResponse = await response.json();

      if (result.success && result.data) {
        // 保存认证信息
        tokenManager.setToken(result.data.token);
        userManager.setUser(result.data.user);
        setUser(result.data.user);
        setToken(result.data.token);

        return { success: true, message: result.message };
      } else {
        return { success: false, message: result.message || '登录失败' };
      }
    } catch (error) {
      console.error('登录失败:', error);
      return { success: false, message: '登录失败，请稍后重试' };
    }
  };

  // 登出函数
  const logout = () => {
    clearAuth();
    setUser(null);
    setToken(null);
    message.success('已成功退出登录');
    router.push('/login');
  };

  // 初始化认证状态
  useEffect(() => {
    const initAuth = async () => {
      setIsLoading(true);
      
      // 如果是公开路由，不需要检查认证
      if (isPublicRoute(pathname)) {
        setIsLoading(false);
        return;
      }

      const isAuthenticated = await checkAuth();
      
      if (!isAuthenticated) {
        // 如果未认证且不是公开路由，重定向到登录页
        router.push('/login');
      }
      
      setIsLoading(false);
    };

    initAuth();
  }, [pathname, router]);

  // 路由变化时检查权限
  useEffect(() => {
    if (!isLoading && !isPublicRoute(pathname) && !user) {
      router.push('/login');
    }
  }, [pathname, user, isLoading, router]);

  const value: AuthContextType = {
    user,
    token,
    isLoading,
    isAuthenticated: !!user && !!token,
    login,
    logout,
    checkAuth,
  };

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  );
};

// Hook for using auth context
export const useAuth = (): AuthContextType => {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
};

// HOC for protected routes
export function withAuth<P extends object>(
  Component: React.ComponentType<P>,
  requiredRoles?: string[]
) {
  return function AuthenticatedComponent(props: P) {
    const { user, isLoading } = useAuth();
    const router = useRouter();

    useEffect(() => {
      if (!isLoading) {
        if (!user) {
          router.push('/login');
          return;
        }

        if (requiredRoles && requiredRoles.length > 0) {
          if (!requiredRoles.includes(user.role)) {
            message.error('您没有权限访问此页面');
            router.back();
            return;
          }
        }
      }
    }, [user, isLoading, router]);

    if (isLoading) {
      return <div>Loading...</div>;
    }

    if (!user) {
      return null;
    }

    if (requiredRoles && requiredRoles.length > 0 && !requiredRoles.includes(user.role)) {
      return null;
    }

    return <Component {...props} />;
  };
} 